<template>
  <div>
    <el-dialog :visible.sync="$parent.openArea" :title="title">
      <div class="dialog_div">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="区域名称" prop="areaName">
            <el-input v-model="formData.areaName" placeholder="请输入区域名称" :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
          <el-form-item label="包含位置" prop="places">
            <el-select v-model="formData.places" placeholder="请选择包含位置" multiple :style="{ width: '100%' }">
              <el-option v-for="(item, index) in placesOptions" :key="index"
                :label="`${item.placeName}(${item.placeNum})设备数量  ${item.equipmentCount}`"
                :disabled="item.equipmentCount == 0" :value="item.placeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置所属" prop="position">
            <el-select v-model="formData.position" placeholder="请选择位置所属" style="width:100%">
              <el-option v-for="(dict, index) in ['室内位置', '室外位置']" :key="index" :label="dict" :value="index + ''">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="建筑物名称" prop="building" v-if="formData.position === '0'">
            <el-select v-model="formData.building" placeholder="请选择建筑物名称" style="width:100%">
              <el-option v-for="(dict, index) in dict.type.building_name" :key="index" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置坐标" prop="longitude">
            <el-button v-show="!bodyshow" type="primary" @click="() => bodyshow = !bodyshow" plain>打开位置</el-button>
            <!-- <div class="map_body"> -->
            <div v-show="bodyshow" class="map_body" id="container"></div>
            <!-- </div> -->
            <el-button v-show="bodyshow" class="map_buttom" icon="el-icon-check" @click="() => bodyshow = !bodyshow"
              circle></el-button>
            <el-input v-show="bodyshow" v-model="inputMap" id="input_id" class="map_input"
              @keyup.enter.native="handleSearch" placeholder="请输入搜索内容">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            <br>
            经度:{{ formData.longitude || '-' }} 纬度:{{ formData.latitude || '-' }}
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"
              :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" align="center">
        <el-button @click="() => $parent.openArea = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getplacelist, addarealist, putUpdatearealist } from "@/api/equipment/equipment.js";
import AMapLoader from '@amap/amap-jsapi-loader';
import Assay from '@/assets/images/u9988.png';
//安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '249c8810513321911bf1b25c975e075b',
}
export default {
  components: {},
  props: ['title', 'rowObj'],
  dicts: ['building_name'],
  data () {
    return {
      bodyshow: false,
      inputMap: '',
      formData: {
        areaName: undefined,
        places: undefined,
        "position": "0",    //位置所属（0室内位置 1室外位置）
        "building": "",    //建筑物名称 关联字典
        "longitude": '', //经度
        "latitude": '',  //纬度
        remark: undefined,
      },
      rules: {
        areaName: [{
          required: true,
          message: '请输入区域名称',
          trigger: 'blur'
        }],
        places: [{
          required: true,
          trigger: 'change',
          validator: ((rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('请选择包含位置!'));
            } else {
              callback()
            }
          })
        }],
        remark: [{
          required: false,
          message: '请输入备注',
          trigger: 'blur'
        }],
        position: { required: true, message: '必填', trigger: 'blur' },
        building: { required: true, message: '必填', trigger: 'blur' },
        longitude: { required: true, message: '必填', trigger: 'blur' },
      },
      placesOptions: [],
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.getList()
  },
  methods: {
    getList () {//初始化数据
      getplacelist({ equipmentCount: -1 }).then(res => {
        this.placesOptions = res.data
      })
      if (this.title === '修改区域') {//修改进入
        this.formData = {
          ...this.rowObj,
          places: this.rowObj.places.map(item => { return item.placeId })
        }
      }
      //DOM初始化完成进行地图初始化
      this.initMap();
    },
    initMap () {
      const th = this
      AMapLoader.load({
        key: "d3c2d6765613d9728729a9c9afe9b78b",    // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.AutoComplete", "AMap.PlaceSearch", "AMap.ControlBar", "AMap.MouseTool"],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map("container", {  //设置地图容器id
          viewMode: "2D",    //是否为3D地图模式
          zoom: 12,           //初始化地图级别
          center: this.title === '修改区域' ? [th.formData.longitude, th.formData.latitude] : '', //初始化地图中心点位置
          resizeEnable: true,
          mapStyle: 'amap://styles/blue', //设置地图的显示样式
        });
        //默认定位当前城市中心点,为新增情况下
        if (this.title !== '修改区域') {
          th.formData.longitude = th.map.getCenter().lng
          th.formData.latitude = th.map.getCenter().lat
        }
        var icon = new AMap.Icon({
          size: new AMap.Size(28, 28),    // 图标尺寸
          image: Assay,  // Icon的图像
          // imageOffset: new AMap.Pixel(0, -60),  // 图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(28, 28)   // 根据所设置的大小拉伸或压缩图片
        });
        var marker = new AMap.Marker({
          offset: new AMap.Pixel(-13, -26),
          position: new AMap.LngLat(th.formData.longitude, th.formData.latitude),
          icon: icon,
        });
        this.map.on('click', function (e) {
          th.formData.longitude = e.lnglat.getLng()
          th.formData.latitude = e.lnglat.getLat()
          marker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()])
          th.map.panTo(marker.getPosition());
          console.log("经度", e.lnglat.getLng())
          console.log("纬度", e.lnglat.getLat())
        });

        let text = `<div style='background-color:rgb(26, 250, 41, 0);color:#feb02c;padding:5px 10px;border-radius:3px;'>经度:${th.formData.longitude},纬度:${th.formData.latitude}</div>`
        // 创建 infoWindow 实例	
        var infoWindow = new AMap.InfoWindow({
          content: text,  //传入 dom 对象，或者 html 字符串
          isCustom: true,  //使用自定义窗体
          anchor: 'top-center',
        });
        marker.on('mouseover', function (e) {//标记鼠标悬浮
          infoWindow.setContent(`<div style='background-color:rgb(26, 250, 41, 0);color:#feb02c;padding:5px 10px;border-radius:3px;'>经度:${th.formData.longitude},纬度:${th.formData.latitude}</div>`)
          infoWindow.open(th.map, [th.formData.longitude, th.formData.latitude]);
        });
        marker.on('mouseout', function (e) {//标记鼠标离开
          infoWindow.close();
        });
        // AMap.plugin('AMap.AutoComplete', function () {
        // 实例化AutoComplete
        var autoOptions = {
          // 使用联想输入的input的id
          input: "input_id"
        }
        var autocomplete = new AMap.Autocomplete(autoOptions)
        // 无需再手动执行search方法，autoComplete会根据传入input对应的DOM动态触发search
        th.placeSearch = new AMap.PlaceSearch({
          map: th.map
        })
        autocomplete.on('select', (e) => {
          th.placeSearch.search(e.poi.name)
          th.formData.longitude = e.poi.location.lng
          th.formData.latitude = e.poi.location.lat
          marker.setPosition([e.poi.location.lng, e.poi.location.lat]) //更新标记点位置
          th.map.panTo(marker.getPosition());
        })
        // })
        this.map.addControl(new AMap.Scale());
        this.map.add(marker)
        // this.map.setFitView()
      }).catch(e => {
        console.log(e);
      })
    },
    handleSearch (e) {
      console.log(e);
      if (e.poi) {
        this.placeSearch.search(e.poi.name)
      } else {
        this.placeSearch.search(this.inputMap)
      }
    },
    handleConfirm () {//提交方法
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.title === '修改区域') {
          let params = {
            ...this.formData,
            places: this.formData.places.map(item => { return { placeId: item } })
          }
          putUpdatearealist(params).then(res => {
            this.$emit('handleSelectList')
            this.$message.success(res.msg)
          })
        } else {
          let params = {
            ...this.formData,
            places: this.formData.places.map(item => { return { placeId: item } })
          }
          addarealist(params).then(res => {
            this.$parent.openArea = false
            this.$emit('handleSelectList')
            this.$message.success(res.msg)
          })
        }

      })
    },
  }
}

</script>
<style lang="scss" scoped>
.dialog_div {
  width: 60%;
  margin: 0 auto;
}

#container {
  padding: 0px;
  margin: 0px;
  // width: 100%;
  // height: 250px;
}

.map_body {
  position: fixed;
  cursor: default;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1;
}

.map_buttom {
  position: fixed;
  top: 20px;
  right: 50px;
  z-index: 2;
}

.map_input {
  width: 280px;
  position: fixed;
  top: 20px;
  left: 50px;
  z-index: 2;
}
</style>
<style>
.amap-sug-result {
  z-index: 9999 !important;
}
</style>
